package com.example.synthesize.多线程.同步工具类countdownlatch;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
 * Created by IntelliJ IDEA2022.3.2
 * @Author: Tenghw
 * @Date: 2023/03/19  20:56
 * @Description: 线程同步工具之CountDownLatch使用
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        test();
    }
    public static void test() throws InterruptedException {
        final CountDownLatch countDownLatch = new CountDownLatch(5);
        for(int i=0;i<5;i++){
            new Thread(()->{
                try {
                    System.out.println("开始线程===>"+Thread.currentThread().getName());
                    Thread.sleep(6);
                    System.out.println("结束线程===>"+Thread.currentThread().getName());
                }catch (Exception e){

                }finally {
                    countDownLatch.countDown();
                }
            }).start();
        }
        System.out.println("开始等待线程执行完成");
        // 等待所有线程执行完成之后才会返回
        countDownLatch.await(4, TimeUnit.SECONDS);
        System.out.println("全部线程执行完成");
    }
}
